package de.uni.muenster.idw2.location.bluetooth.service;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import android.os.Environment;
import android.util.Log;

public class DataIO {

	public static ArrayList<BluetoothHost> allHosts;
	//String filename = "/sdcard/BTTracking/allHosts.txt"; 
	public static String filename = Environment.getExternalStorageDirectory() + "/allHosts.txt"; 	
   
	/*
	 * reads text-file with host names + host-coordinates
	 * example
	 * String, Integer, Integer, Integer
	 * 14:22:33:44:55:66,300,300,1
	 */
	
	public static ArrayList<BluetoothHost> readAllHosts() throws IOException{
		allHosts = new ArrayList<BluetoothHost>();
		FileReader fr = new FileReader(filename);
		try {
			BufferedReader br = new BufferedReader(fr);
		    String line = br.readLine();
		    while (line != null) {
			  Log.i("AMK", line);
			  String[] splittArray = line.split(",");
			  allHosts.add(new BluetoothHost(splittArray[0].trim(), Float.parseFloat(splittArray[1].trim()), Float.parseFloat(splittArray[2].trim()), Integer.parseInt(splittArray[3].trim())));
			  line = br.readLine();
		    }
		    br.close();
		    Log.i("AMK", "Anzahl geladenener Hosts:"+allHosts.size());
		    return allHosts;
		} catch (Exception e) {
			Log.e("AMK", "Fehler beim Lesen der Hosts");
		}
		return null;
	}
	
	public static float[] getHostsPositionInFloorAsFloatArray(int floor){
		if (allHosts == null) {
			 try {
				DataIO.readAllHosts();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		//the positions in WGS84
		int i = 0;
		float [] positions = new float[DataIO.allHosts.size()*3];
		//get only the dongles that are placed in the floor
		for(BluetoothHost host : DataIO.allHosts){
		  if (host.getBthFloor() == floor) {	
		    positions[i++] = host.getBthX();
		    positions[i++] = host.getBthY();
		    positions[i++] = host.getBthFloor();
		  }
		}	
		return positions;
	}
	
	public static int getFloorForHost(String hostAddress){
		for(BluetoothHost host : DataIO.allHosts){
			  if (host.getBthAdress().equals(hostAddress)) 	
                 return host.getBthFloor();
		}
		return Integer.MIN_VALUE;
	} 
}
